package com.whut.filter;

import com.alibaba.fastjson.JSON;
import com.whut.common.BaseContext;
import com.whut.common.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    // 定义路径匹配器，可以支持通配符的模式
    // 将匹配器定义为一个全局的静态对象，可以被所有请求线程共享，从而提高效率
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        // 0，对传入的参数进行处理
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1.获取本次请求
        final String requestURI = request.getRequestURI();

        log.info("拦截请求：{}", requestURI);

        // 2.判断本次请求是否需要处理
        // 定义不需要处理的请求路径有哪些
        String[] urls = new String[]{
                "/backend/admin/login.do",
                "/admin/logout.do",
                "/backend/**",
                "/front/**",
                "/wx/loginSms.do",  //移动端发送短信
                "/wx/login.do",     //移动端登录
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        boolean match = false;
        for (String url : urls){
            // 将获得的请求与urls中的每一个url模式进行匹配
            match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                break;
            }
        }

        if (match){
            log.info("本次请求不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }


        // 3.如果不需要处理，则直接放行
        if (match){
            log.info("本次请求不需要处理", requestURI);
            // 调用过滤器的
            filterChain.doFilter(request, response);
            return;
        }

        //4.判断为登录状态，如果已登录
        // 针对后台服务端用户
        if (request.getSession().getAttribute("Admin") != null){
            log.info("用户已登录，用户id为：{}", request.getSession().getAttribute("Admin"));

            // 获得当前登录用户的id
            Long empId = (long)request.getSession().getAttribute("Admin");
            // 并将当前登录用户id绑定到当前处理线程上
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return;
        }
        // 针对移动端用户
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }
        // 针对移动端快递员
        if (request.getSession().getAttribute("courier") != null) {
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("courier"));

            Long userId = (Long)request.getSession().getAttribute("courier");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }
        log.info("用户未登录");

        // 5.如果未登录
        response.getWriter()
                .write(JSON.toJSONString(Message.error("NOTLOGIN")));
        return;
    }

}